<template>
    <div>
        <div style="display: flex; justify-content: space-between; align-items: center;">
            <div v-show="user_name && user_name!=''">
                <span> 用户{{ user_name }}</span>
                <a-button type="primary" @click="logout">退出</a-button>
            </div>
            <div v-show="!user_name || user_name==''">
                <a-input v-model:value="user.username" placeholder="请输入用户名" style="width: 200px;" />
                <a-input v-model:value="user.password" placeholder="请输入密码" style="width: 200px;" />
                <a-button type="primary" @click="login">登录</a-button>
            </div>
        </div>

        <a-tabs v-model:activeKey="topActiveKey" size="large">
            <a-tab-pane key="1" :tab="`消息${totalUnread.value > 0 ? ' (' + totalUnread.value + ')' : ''}`">
                <a-tabs v-model:activeKey="leftActiveKey" tab-position="left">
                    <a-tab-pane
                    v-for="item in chatList"
                    :key="item.id"
                    :tab="`${item.name}${item.unread > 0 ? ' (' + item.unread + ')' : ''}`"
                    >
                    <ChatPanel :chatType="item.type" :chatId="item.id" :chatName="item.name" />
                    </a-tab-pane>
                </a-tabs>

            </a-tab-pane>
            <a-tab-pane key="2" tab="联系人" force-render>Content of Tab Pane 2</a-tab-pane>
        </a-tabs>
    </div>
</template>

<script setup lang="ts">

import * as signalR from "@microsoft/signalr";
import { message } from "ant-design-vue";
import { onMounted, ref,watch,computed  } from "vue";
import ChatPanel from './chat/index.vue';
import { history } from '@/api/chat';
import type { ChatItem } from "@/types/chat/index";
import type { LoginInput,LoginResponse } from "@/types/login";
import { useUserStore } from "@/store/modules/user"; 
import { storeToRefs } from "pinia";
const userStore = useUserStore();
const { user_name,user_token } =  storeToRefs(userStore);

let hubUrl = `${import.meta.env.VITE_APP_BASE_API}/hub`;

//.net core 版本中默认不会自动重连，需手动调用 withAutomaticReconnect 
const connection = new signalR.HubConnectionBuilder()
      .withAutomaticReconnect()//断线自动重连
      .withUrl(hubUrl,{ accessTokenFactory: () => user_token.value })//传递参数Query["access_token"]
      .build();

//启动
connection.start().catch(err => {
  console.log(err);
});

//自动重连成功后的处理
connection.onreconnected(connectionId => {
    console.log(connectionId);
});

const groupName= ref("")
const user = ref<LoginInput>({
    username: "",
    password: ""
})
const msg = ref("")
const remsg = ref("")

const handle = () => {

    if(msg.value.trim()==""){
        message.warning("不能发送空白消息");
        return;
    }
    
    if(groupName.value.length>0){
        //组聊天（要先进群组）
        connection.invoke("SendMessageToGroup", groupName.value, user.value, msg.value);
    }else{
        //世界聊天
        connection.invoke("SendMessage", user.value, msg.value);
    }
    msg.value = "";
}


//创建账号进入
const login =()=>{
    //必须输入账号密码
    if(!user.value || user.value.username.length==0 || user.value.password.length==0)
        return message.warning('请先输入账号密码')
    //请求登录接口
    userStore.login(user.value).then((res:LoginResponse) => {
        if (res.code == 20000) {
            message.success("登录成功");
            connection.start().then(() => {
                //登录后接入signalr
                connection.invoke("Login", res.data.id);
            });
        } else {
            message.error('登录失败');
        }
    })
}
const logout = () => {
    userStore.logout()
    connection.stop();
    message.success("退出成功");
}

onMounted(async ()=>{
//调用后端方法 SendMessageResponse 接收定时数据
    connection.on("JoinGroupNotice", function(groupName,user) {
          remsg.value += "\r\n" + user + "加入了当前群聊";
    });

     //调用后端方法 SendMessage 接受自己人发送消息
    connection.on("ReceiveMessage", function(user,message:ChatItem) {
        console.log(user,message)
        remsg.value += "\r\n"  + user + ":" + message;

        let chat = chatList.value.find(item => item.id === message.id);
        if (!chat) {
            // 新对象，自动加tab
            chat = {
            id: message.id,
            name: message.name, // 或后端返回的name
            type: message.type,
            unread: message.unread || 0,
            };
            chatList.value.push(chat);
        } else {
            chat.unread = (chat.unread || 0) + 1;
        }
    });
    // 你可以在收到后端消息通信后再次调用 fetchChatList()，例如：
    connection.on("SomeBackendEvent", () => {
        fetchChatList();
    });
    
    console.log('user_token.value',user_token.value)
    // 获取聊天对象列表（首次加载）
    if(user_token.value && user_token.value != ""){
        await fetchChatList();
    }

   

})
// 封装获取聊天对象列表的方法
const fetchChatList = async () => {
    const res = await history();
    chatList.value = res.data;
    if (chatList.value.length > 0) {
        leftActiveKey.value = chatList.value[0].id;
    }
};
const totalUnread = computed(() =>
  chatList.value.reduce((sum, item) => sum + (item.unread || 0), 0)
);
const topActiveKey = ref('1');
const leftActiveKey = ref('1')
const TopTabItems = Array.from({ length: 3 }).map((_, i) => {
      const id = String(i + 1);
      return {
        label: `Tab ${id}`,
        key: id,
        children: `Content of Tab Pane ${id}`,
      };
    })

const chatList = ref<any[]>([]);

watch(leftActiveKey, (newVal) => {
  const chat = chatList.value.find(item => item.id === newVal);
  if (chat) chat.unread = 0;
});
</script>
<style scoped>
</style>